﻿unit IdTCPClientPool;

interface

uses
  System.SysUtils, System.Generics.Collections,
  IdGlobal, IdTCPClient;

type
  hashRecord = record
    hash: uint32;
    enable: boolean;
  end;

  TIdTCPClientPool = class
  private
    FPool: TStack<TIdTCPClient>;
    FMaxConnections: Integer;
  public
    constructor Create(const AMaxConnections: Integer);
    destructor Destroy; override;
    function GetConnection: TIdTCPClient;
    procedure ReleaseConnection(AConnection: TIdTCPClient);
  end;

implementation

uses IdIOHandlerStack;

constructor TIdTCPClientPool.Create(const AMaxConnections: Integer);
var
  i: Integer;
  Client: TIdTCPClient;
begin
  inherited Create;
  FMaxConnections := AMaxConnections;
  FPool := TStack<TIdTCPClient>.Create;

  // 预先创建连接
  for i := 1 to FMaxConnections do
  begin
    Client := TIdTCPClient.Create;
    try
      Client.IOHandler := TIdIOHandlerStack.Create(Client);
      Client.IOHandler.DefStringEncoding := IndyTextEncoding_UTF8;
      Client.IPVersion := ID_IPv6;
      Client.ConnectTimeout := 2000;
      Client.readTimeout := 2000;
      FPool.Push(Client);
    except
      Client.Free;
      raise; // 或者处理连接失败的情况
    end;
  end;
end;

function TIdTCPClientPool.GetConnection: TIdTCPClient;
begin
  if FPool.Count > 0 then
    Result := FPool.Pop
  else
    raise Exception.Create('连接池已耗尽');
end;

procedure TIdTCPClientPool.ReleaseConnection(AConnection: TIdTCPClient);
begin
  // 重要：清空输入缓冲区，避免旧数据干扰
  AConnection.IOHandler.InputBuffer.Clear;
  AConnection.DisconnectNotifyPeer;
  // 将连接放回池中
  FPool.Push(AConnection);
end;

destructor TIdTCPClientPool.Destroy;
var
  Client: TIdTCPClient;
begin
  while FPool.Count > 0 do
  begin
    Client := FPool.Pop;
    Client.Disconnect;
    Client.Free;
  end;
  FPool.Free;
  inherited;
end;

end.
